"""
有声读物实体模型
"""

from sqlalchemy import (
    Column, String, Text, Float, Integer, DateTime, 
    Boolean, JSON, ForeignKey, Enum as SQLEnum
)
from datetime import datetime
from sqlalchemy.orm import relationship, declarative_base
from sqlalchemy.dialects.postgresql import UUID
from datetime import datetime
from enum import Enum
import uuid

from ..core.database import Base


class AudioBookStatus(Enum):
    """有声读物状态"""
    PENDING = "pending"        # 待处理
    PROCESSING = "processing"  # 处理中
    COMPLETED = "completed"    # 已完成
    FAILED = "failed"          # 失败
    DELETED = "deleted"        # 已删除


class AudioBook(Base):
    """有声读物模型"""
    __tablename__ = "audiobooks"
    
    id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
    title = Column(String(200), nullable=False, index=True)
    author = Column(String(100), nullable=True)
    description = Column(Text, nullable=True)
    language = Column(String(10), nullable=False, default="zh-CN")
    
    # 状态信息
    status = Column(SQLEnum(AudioBookStatus), default=AudioBookStatus.PENDING, index=True)
    progress = Column(Float, default=0.0)  # 处理进度 0-1
    
    # 音频信息
    total_duration = Column(Float, default=0.0)  # 总时长(秒)
    chapters_count = Column(Integer, default=0)   # 章节数量
    format = Column(String(10), default="mp3")     # 音频格式
    sample_rate = Column(Integer, default=22050)   # 采样率
    bitrate = Column(Integer, default=128)         # 比特率
    
    # 文件路径
    file_path = Column(String(500), nullable=True)
    cover_image_path = Column(String(500), nullable=True)
    
    # 元数据
    book_metadata = Column(JSON, nullable=True)  # 存储额外信息
    
    # 用户关联
    user_id = Column(String, nullable=False, index=True)
    
    # 时间戳
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
    completed_at = Column(DateTime, nullable=True)
    
    # 关系
    chapters = relationship("AudioBookChapter", back_populates="audiobook", cascade="all, delete-orphan")
    streams = relationship("AudioStream", back_populates="audiobook", cascade="all, delete-orphan")
    
    def __repr__(self):
        return f"<AudioBook(id='{self.id}', title='{self.title}', status='{self.status.value}')>"
    
    def to_dict(self):
        """转换为字典"""
        return {
            "id": self.id,
            "title": self.title,
            "author": self.author,
            "description": self.description,
            "language": self.language,
            "status": self.status.value,
            "progress": self.progress,
            "total_duration": self.total_duration,
            "chapters_count": self.chapters_count,
            "format": self.format,
            "sample_rate": self.sample_rate,
            "bitrate": self.bitrate,
            "file_path": self.file_path,
            "cover_image_path": self.cover_image_path,
            "metadata": self.metadata,
            "user_id": self.user_id,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None,
            "completed_at": self.completed_at.isoformat() if self.completed_at else None
        }


class AudioBookChapter(Base):
    """有声读物章节模型"""
    __tablename__ = "audiobook_chapters"
    
    id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
    audiobook_id = Column(String, ForeignKey("audiobooks.id"), nullable=False, index=True)
    
    # 章节信息
    title = Column(String(200), nullable=False)
    order = Column(Integer, nullable=False)  # 章节顺序
    content = Column(Text, nullable=False)  # 章节内容
    
    # 音频信息
    duration = Column(Float, default=0.0)    # 时长(秒)
    file_path = Column(String(500), nullable=True)  # 音频文件路径
    file_size = Column(Integer, default=0)    # 文件大小(字节)
    
    # 语音配置
    voice_id = Column(String, nullable=True)     # 语音ID
    voice_preset = Column(String, nullable=True)  # 语音预设
    voice_settings = Column(JSON, nullable=True)  # 语音设置
    
    # 状态信息
    status = Column(SQLEnum(AudioBookStatus), default=AudioBookStatus.PENDING)
    progress = Column(Float, default=0.0)  # 处理进度
    
    # 时间戳
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
    completed_at = Column(DateTime, nullable=True)
    
    # 关系
    audiobook = relationship("AudioBook", back_populates="chapters")
    
    def __repr__(self):
        return f"<AudioBookChapter(id='{self.id}', title='{self.title}', order={self.order})>"
    
    def to_dict(self):
        """转换为字典"""
        return {
            "id": self.id,
            "audiobook_id": self.audiobook_id,
            "title": self.title,
            "order": self.order,
            "content": self.content,
            "duration": self.duration,
            "file_path": self.file_path,
            "file_size": self.file_size,
            "voice_id": self.voice_id,
            "voice_preset": self.voice_preset,
            "voice_settings": self.voice_settings,
            "status": self.status.value,
            "progress": self.progress,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None,
            "completed_at": self.completed_at.isoformat() if self.completed_at else None
        }


class AudioBookProgress(Base):
    """有声读物阅读进度模型"""
    __tablename__ = "audiobook_progress"
    
    id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
    audiobook_id = Column(String, ForeignKey("audiobooks.id"), nullable=False, index=True)
    user_id = Column(String, nullable=False, index=True)
    
    # 进度信息
    current_chapter = Column(Integer, default=0)      # 当前章节
    current_position = Column(Float, default=0.0)     # 当前位置(秒)
    total_progress = Column(Float, default=0.0)       # 总体进度(0-1)
    
    # 阅读统计
    total_read_time = Column(Float, default=0.0)      # 总阅读时间(秒)
    last_read_at = Column(DateTime, nullable=True)   # 最后阅读时间
    chapter_progress = Column(JSON, nullable=True)   # 各章节进度
    
    # 书签
    bookmarks = Column(JSON, nullable=True)          # 书签位置
    
    # 时间戳
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
    
    def __repr__(self):
        return f"<AudioBookProgress(id='{self.id}', user_id='{self.user_id}', progress={self.total_progress})>"
    
    def to_dict(self):
        """转换为字典"""
        return {
            "id": self.id,
            "audiobook_id": self.audiobook_id,
            "user_id": self.user_id,
            "current_chapter": self.current_chapter,
            "current_position": self.current_position,
            "total_progress": self.total_progress,
            "total_read_time": self.total_read_time,
            "last_read_at": self.last_read_at.isoformat() if self.last_read_at else None,
            "chapter_progress": self.chapter_progress,
            "bookmarks": self.bookmarks,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None
        }


class AudioBookReview(Base):
    """有声读物评论模型"""
    __tablename__ = "audiobook_reviews"
    
    id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
    audiobook_id = Column(String, ForeignKey("audiobooks.id"), nullable=False, index=True)
    user_id = Column(String, nullable=False, index=True)
    
    # 评论信息
    rating = Column(Integer, nullable=False)         # 评分 1-5
    title = Column(String(200), nullable=True)       # 评论标题
    content = Column(Text, nullable=True)            # 评论内容
    
    # 统计信息
    helpful_count = Column(Integer, default=0)       # 有用数
    is_public = Column(Boolean, default=True)        # 是否公开
    
    # 时间戳
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
    
    def __repr__(self):
        return f"<AudioBookReview(id='{self.id}', rating={self.rating}, user_id='{self.user_id}')>"
    
    def to_dict(self):
        """转换为字典"""
        return {
            "id": self.id,
            "audiobook_id": self.audiobook_id,
            "user_id": self.user_id,
            "rating": self.rating,
            "title": self.title,
            "content": self.content,
            "helpful_count": self.helpful_count,
            "is_public": self.is_public,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None
        }


class AudioBookTag(Base):
    """有声读物标签模型"""
    __tablename__ = "audiobook_tags"
    
    id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
    audiobook_id = Column(String, ForeignKey("audiobooks.id"), nullable=False, index=True)
    user_id = Column(String, nullable=False, index=True)
    
    # 标签信息
    tag = Column(String(50), nullable=False, index=True)
    color = Column(String(7), nullable=True)       # 标签颜色
    
    # 时间戳
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    
    def __repr__(self):
        return f"<AudioBookTag(id='{self.id}', tag='{self.tag}', audiobook_id='{self.audiobook_id}')>"
    
    def to_dict(self):
        """转换为字典"""
        return {
            "id": self.id,
            "audiobook_id": self.audiobook_id,
            "user_id": self.user_id,
            "tag": self.tag,
            "color": self.color,
            "created_at": self.created_at.isoformat() if self.created_at else None
        }
